package com.heima.search.service;
// 爱情不是随便许诺,算了,不想再说了

import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.search.entiry.ArticleDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ApSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 批量导入
     *
     * @param articleDtoList
     */
    public void importArticle(List<ArticleDto> articleDtoList) {

        BulkRequest bulkRequest = new BulkRequest();


        List<ArticleDoc> articleDocList = BeanHelper.copyWithCollection(articleDtoList, ArticleDoc.class);

        for (ArticleDoc articleDoc : articleDocList) {
            // 索引库名
            IndexRequest request = new IndexRequest("app_info_article").id(articleDoc.getId().toString()).source(JsonUtils.toString(articleDoc), XContentType.JSON);

            bulkRequest.add(request);
        }

        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
